#include "bsp_spi.h"

void spi_master_init(ECSPI_Type * base , unsigned char channel){
    
    //清0，CONREG[EN]位以关闭时钟，复位ECSPI
    base->CONREG = 0;
    //配置SPI触发模式以及burst_length
    base->CONREG |= (1<<3) | (7<<20);
    //配置spi启用的通道
    base->CONREG |= ((1<<channel)<<4);
    //配置spi启用的时钟分频
    base->CONREG |= (9<<12);
    //启用SPI
    base->CONREG |= (1<<0);

    //配置CONFIGREG寄存器
    base->CONFIGREG = 0;
    //配置PERIODREG寄存器
    base->PERIODREG = 0X2000;

    //开启回环测试
    base->TESTREG |= (1<<31);

} 

void spi_write_byte(ECSPI_Type *base,unsigned char txdata,unsigned char channel){
    uint32_t spirxdata = 0;
    uint32_t spitxdata = txdata;

    /* 选择通道*/
    base->CONREG &= ~(3 << 18);
    base->CONREG |= (channel << 18);

    while((base->STATREG & (1 << 0)) == 0); /* 等待发送 FIFO 为空 */
    base->TXDATA = spitxdata;
}

unsigned char spi_read_byte(ECSPI_Type *base){
    uint32_t spirxdata = 0;
    while((base->STATREG & (1 << 3)) == 0); /* 等待接收 FIFO 有数据 */
    spirxdata = base->RXDATA;
    return spirxdata;

}

unsigned char spi_readwrite_byte(ECSPI_Type *base,unsigned char txdata,unsigned char channel){
    uint32_t spirxdata = 0;
    uint32_t spitxdata = txdata;

     /* 选择通道*/
    base->CONREG &= ~(3 << 18);
    base->CONREG |= (channel << 18);

    while((base->STATREG & (1 << 0)) == 0); /* 等待发送 FIFO 为空 */
    base->TXDATA = spitxdata;

    while((base->STATREG & (1 << 3)) == 0); /* 等待接收 FIFO 有数据 */
    spirxdata = base->RXDATA;
    
    return spirxdata;
}